package com.quzhi.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quzhi.common.Result;
import com.quzhi.sys.dto.UserDto;
import com.quzhi.sys.entity.Role;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.entity.UserRole;
import com.quzhi.sys.mapper.RoleMapper;
import com.quzhi.sys.mapper.UserMapper;
import com.quzhi.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private UserRoleServiceImpl userRoleService;


    @Override
    public Result<?> login(User user) {
        // 查询数据库
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());

        User loginUser = this.baseMapper.selectOne(wrapper);

        // 比对密码,并且密码匹配

        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {
            // 判断用户是否警用
            if (loginUser.getStatus() == 0) {
                return Result.fail(20002, "该用户状态为禁用状态");
            }
            // 登录成功
            // 生成token,并且用户信息放在Redis里面
            String key = "user:" + UUID.randomUUID();

            loginUser.setPassword(null);
            redisTemplate.opsForValue().set(key, loginUser, 24 * 60, TimeUnit.MINUTES);

            // 返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", key);

            return Result.success(data);
        }

        return Result.fail("密码或用户名错误");

    }


    @Override
    public Map<String, Object> getUserinfo(String token) {
        // 查询redis中的用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null) {
            // 将数据转成json数据
            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);

            Map<String, Object> data = new HashMap<>();
            data.put("userId", loginUser.getId());
            data.put("name", loginUser.getUsername());
            data.put("avatar", loginUser.getAvatar());

            List<String> roleList = this.baseMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles", roleList);

            return data;
        }
        return null;
    }


    public User getUserinfoForBack(String token) {
        // 查询redis中的用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null) {
            // 将数据转成json数据
            return JSON.parseObject(JSON.toJSONString(obj), User.class);
        }
        return null;
    }

    public void logout(String qzToken) {
        redisTemplate.delete(qzToken);
    }

    public Result<?> addUser(UserDto user) {
        // 设置ID
        String uuid = UUID.randomUUID().toString();
        user.setId(uuid);
        // 默认不删除
        user.setDeleted(0);

        // 设置一个默认头像
        user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 更具用户名查询数据库
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        List<User> users = this.baseMapper.selectList(wrapper);

        if (users.size() == 0) {
            // 添加权限
            // 更具权限查询权限对应的Id
            for (String addRole : user.getRoles()) {
                LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Role::getRoleDesc, addRole);
                Role role = roleService.getOne(queryWrapper);

                // 向用户权限表中添加数据
                UserRole userRole = new UserRole();
                userRole.setId(UUID.randomUUID().toString());
                userRole.setUserId(user.getId());
                userRole.setRoleId(role.getRoleId());
                userRoleService.save(userRole);
            }

            // 用户名不存在添加用户
            this.baseMapper.insert(user);

            return Result.success("新增用户成功");
        } else {
            return Result.fail("用户名已存在");
        }

    }

    @Override
    public Result<?> updateUser(UserDto user) {

        // 刪除用戶原有的所有权限
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, user.getId());
        userRoleService.remove(wrapper);

        // 添加新权限
        List<String> roles = user.getRoles();
        for (String role : roles) {
            UserRole userRole = new UserRole();
            userRole.setId(UUID.randomUUID().toString());

            // 更具权限名称查询选项ID
            LambdaQueryWrapper<Role>  roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roleLambdaQueryWrapper.eq(Role::getRoleDesc, role);
            Role roleServiceOne = roleService.getOne(roleLambdaQueryWrapper);

            userRole.setRoleId(roleServiceOne.getRoleId());
            userRole.setUserId(user.getId());

            // 添加权限
            userRoleService.save(userRole);
        }


        this.baseMapper.updateById(user);
        return Result.success("修改用户成功");
    }

}
